<?php
include_once 'protocol_includes.php';

    class LoginHandler extends subapplication {
        private $cmd;
        public static $PROTOCOL = "Login";

        public static function create(command $cmd)
        {
            if (!self::IsThisClass($cmd)) return null;
            $N = new LoginHandler($cmd);
            return $N;
        }

        public function __construct(command $cmd)
        {
            $this->cmd  = $cmd;
            $this->Username($cmd->GetData('USERNAME'));
            $this->Password($cmd->GetData('PASSWORD'));
        }

    public function  requiresAuthentication() {
        return false;
    }

        public function execute()
        {
            
            $loginResult = ns_dao_user::authenticateUser($this->Username(), $this->Password());
            switch ($loginResult){
                case (ns_dao_user::$AUTH_FAIL):
                    $this->UpdateResult("NS_PROTOCOL=AuthFailed");
                    break;

                case (ns_dao_user::$AUTH_OK):
                    $this->LoginKey($this->getLoginKey());
                    ns_dao_user::UpdateUsersLastSeenMessage($this->Username());
                    $this->UpdateResult("NS_PROTOCOL=LoginSuccess&NS_LOGINKEY={$this->LoginKey()}");
                    break;
            }
        }
        
        private function getLoginKey(){
            return ns_dao_user::CreateLoginKey($this->Username());
        }

        // =========== PROPERTIES ==========

        private $property = array();
        private function GetSetData($property_name,$value = null)
        {
            if (is_null($value) && isset($this->property[$property_name])) return $this->property[$property_name];
            $this->property[$property_name] = $value;
        }

        public function Username($value = null)
        {
            return $this->GetSetData("USERNAME",$value);
        }

        public function Password($value = null)
        {
            return $this->GetSetData("PASSWORD",$value);
        }
        
        public function LoginKey($value = null)
        {
            return $this->GetSetData("LoginKey",$value);
        }

        public function result()
        {
            $this->cmd->GetResult();
        }

        public function UpdateResult($str)
        {
            $this->cmd->SetResult($str);
        }

        public static function IsThisClass(command $cmd)
        {
            if (!$cmd->HasDataKey('USERNAME')) return false;
            if (!$cmd->HasDataKey('PASSWORD')) return false;

            return true;
        }
    }
?>
